package com.desay.pangoo.itmt.repository.spec;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

/**
 * @author shouyi.huang@desay-svautomotive.com on
 *         2019年7月23日下午8:35:34 @Description： 扩展查询条件
 * @Modified By： [] on [] for [修改说明]
 */
public class ExpandCriteria<T> implements Specification<T> {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8243791261752710279L;
	/**
	 * 
	 */
	private List<ExpandCriterion> criterions = new ArrayList<>();

	@Override
	public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
		List<Predicate> predicates = new ArrayList<>();
		if (!criterions.isEmpty()) {
			for (ExpandCriterion c : criterions) {
				Predicate predicate = c.toPredicate(root, query, builder);
				if (null != predicate) {
					predicates.add(predicate);
				}
			}
		}
		// 去重
		query.distinct(true);
		// 将所有条件用 and 联合起来
		if (!predicates.isEmpty()) {
			return builder.and(predicates.toArray(new Predicate[predicates.size()]));
		}
		return builder.conjunction();
	}

	/**
	 * 增加简单条件表达式
	 *
	 * @param criterion
	 * @Methods Name add
	 */
	public void add(ExpandCriterion criterion) {
		if (criterion != null) {
			criterions.add(criterion);
		}
	}
}
